<template>
  <div class="app-main-container">
    <el-drawer
      ref="drawerRef"
      title="排课"
      :visible.sync="isShowDrawer"
      :before-close="closeDrawer"
      size="1000px"
    >
      <QueryForm
        v-model="filters"
        :query-form-config="queryFormConfig"
        @handleQuery="getList(1)"
        @clear="clearList"
      />
      <div class="doumee_table_header">
        <el-button
          type="primary"
          @click="showSchedule"
        >排课</el-button>
      </div>
      <el-table
        ref="table"
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        :header-row-class-name="'table-header'"
        class="doumee-element-table"
      >
        <el-table-column
          align="center"
          label="课程名称"
          min-width="200"
          prop="courseName"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="上课时间"
          prop="classTime"
          min-width="230"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="上课地点"
          prop="site"
          show-overflow-tooltip
          min-width="200"
        />
        <el-table-column
          align="center"
          label="授课老师"
          prop="teacherName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="学员人数"
          prop="studentNum"
          min-width="100"
        >
          <template slot-scope="scope">
            <span class="pointer primaryColor underline" @click="showStudents(scope.row)">{{ scope.row.studentNum }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="实际上课人数"
          prop="realNum"
          min-width="100"
        />
        <el-table-column
          align="center"
          label="课时状态"
          prop="status"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.status == "0" ? "待上课" : "已上课" }}
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="flex-cc">
              <el-button
                v-if="scope.row.status == 0 "
                type="text"
                @click="showSchedule(scope.row)"
              >编辑</el-button>
              <el-button
                v-if="scope.row.status == 0"
                type="text"
                @click="showStudent(scope.row)"
              >学员管理</el-button>
              <el-button
                v-if="scope.row.status == 0"
                type="text"
                class="secondColor"
                @click="updateStatus(scope.row)"
              >删除</el-button>
              <span v-if="scope.row.status == 1">-</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Paginations
        :total="total"
        :page="pagination.page"
        @current-change="getList"
        @SizeChange="handleSizeChange"
      />
    </el-drawer>
    <el-drawer title="学员管理" :visible.sync="showDetails" size="1000px" :close-on-click-modal="modalDialog" :close-on-press-escape="modalDialog">
      <div class="df mb20">
        <div class="mr30">课程名称：{{ tempCourseRow.courseName }}</div>
        <div class="flex1 mr20">上课时间：{{ tempCourseRow.classTime }}</div>
        <div class="mr30">教练：{{ tempCourseRow.teacherName }}</div>
        <div class="flex1">上课地点：{{ tempCourseRow.site }}</div>
      </div>
      <div class="mb20">
        <span>学员姓名：</span>
        <el-input v-model="studentFilter.studentName" class="w200" placeholder="请输入学员姓名" />
        <span class="ml30">会员信息：</span>
        <el-input v-model="studentFilter.memberInfo" class="w200" placeholder="请输入会员姓名/手机号/卡号" />
        <el-button type="primary" class="ml30" @click="refrshCourseTimeStudentList(1)">查找</el-button>
        <el-button class="ml10" @click="clearStudent">清空</el-button>
      </div>
      <div class="dialog-header" style="display:flex;align-items: center;justify-content: space-between;">
        <el-button
          type="primary"
          @click="toStudentAdd()"
        >添加</el-button>
        <div class="dialog-title">共{{ stuTotal }}名学员，{{ kcStatus == "0" ? "待上课" : "缺席" }}{{ stuTotal - realNum }}名学员</div>
      </div>
      <el-table
        :data="detail"
        border
        fit
        :header-row-class-name="'table-header'"
        class="doumee-element-table margin-t-10"
      >
        <el-table-column align="center" label="学员姓名" prop="studentName" />
        <el-table-column align="center" min-width="250" label="会员信息" prop="phone">
          <template slot-scope="scope">
            <span>{{ scope.row.memberName }}</span>
            <span>-{{ scope.row.memberPhone }}</span>
            <span>-{{ scope.row.memberCard }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" min-width="80" label="上课课时" prop="classNum" />
        <el-table-column align="center" min-width="80" label="剩余课时" prop="num" />
        <el-table-column align="center" min-width="80" label="上课状态" prop="status">
          <template slot-scope="scope">
            {{ scope.row.status == "0" ? "缺席": scope.row.status == "2" ? "待上课" : "已上课 " }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="flex-cc">
              <el-button
                type="text"
                class="secondColor"
                @click="deleteStu(scope.row.id)"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Paginations
        :total="stuTotal"
        :page="studentPagination.page"
        @current-change="refrshCourseTimeStudentList"
        @SizeChange="StuSizeChange"
      />
    </el-drawer>
    <el-dialog
      title="上课学员"
      :visible.sync="isShowStudents"
      width="800px"
    >
      <div class="dialog-title">共{{ stuTotal }}名学员，{{ kcStatus == "0" ? "待上课" : "缺席" }}{{ stuTotal - realNum }}名学员</div>
      <el-table
        :data="detail"
        border
        fit
        :header-row-class-name="'table-header'"
        class="doumee-element-table margin-t-10"
      >
        <el-table-column align="center" label="学员姓名" prop="studentName" />
        <el-table-column align="center" min-width="250" label="会员信息" prop="phone">
          <template slot-scope="scope">
            <span>{{ scope.row.memberName }}</span>
            <span>-{{ scope.row.memberPhone }}</span>
            <span>-{{ scope.row.memberCard }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" min-width="80" label="上课课时" prop="classNum" />
        <el-table-column align="center" min-width="80" label="剩余课时" prop="num" />
        <el-table-column align="center" min-width="80" label="上课状态" prop="status">
          <template slot-scope="scope">
            {{ scope.row.status == "0" ? "缺席": scope.row.status == "2" ? "待上课" : "已上课 " }}
          </template>
        </el-table-column>
      </el-table>
      <Paginations
        :total="stuTotal"
        :page="studentPagination.page"
        @current-change="refrshCourseTimeStudentList"
        @SizeChange="StuSizeChange"
      />
    </el-dialog>
    <!-- 新增学员 -->
    <el-dialog
      title="新增学员"
      :visible.sync="showAddStudent"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      @closed="cancelAddStudent"
    >
      <el-table
        :data="tableData"
        border
        fit
        max-height="500"
        :header-row-class-name="'table-header'"
        class="doumee-element-table margin-t-10"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="rowCanSelect"
        />
        <el-table-column align="center" label="学员名称" prop="studentName" />
        <el-table-column align="center" label="手机号" prop="phone" />
        <el-table-column align="center" label="已签到次数" prop="num">
          <template slot-scope="scope">
            {{ scope.row.num ? scope.row.num : "0" }}
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button @click="cancelAddStudent">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="confirmAddStudent">确定</el-button>
      </span>
    </el-dialog>
    <ScheduleCardAdd v-if="isShowScheduleCardAdd" ref="ScheduleCardAddRef" @close="isShowScheduleCardAdd = false" @success="getList(1)" />
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import store from '@/store'
import {
  courseTimeList,
  courseTimeStudentList,
  deleteCourseTime,
  courseStudentList,
  courseTimeAddStudent,
  courseTimeDelStudent
} from '@/api'
import QueryForm from '@/components/QueryForm'
import ScheduleCardAdd from '../scheduleCardAdd'
export default {
  components: {
    QueryForm,
    ScheduleCardAdd
  },
  data() {
    return {
      isShowDrawer: false,
      isShowStudents: false,
      isShowScheduleCardAdd: false,
      courseId: '',
      classId: '',
      site: '',
      teacherId: '',
      tempCourseRow: {},
      studentFilter: {},
      studentPagination: {
        rows: 10,
        page: 1
      },
      stuTotal: 0,

      queryFormConfig: {
        formItems: [{
          filed: 'classTime',
          type: 'date',
          label: '上课时间',
          placeholder: '请选择上课时间',
          clearable: true,
          pickerOptions: {
            disabledDate(time) {
              return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
            }
          }
        }, {
          filed: 'status',
          type: 'select',
          label: '课程状态',
          placeholder: '请选择课程状态',
          clearable: true,
          options: [
            { value: '0', label: '待上课' },
            { value: '1', label: '已上课' }
          ]
        }],
        online: true
      },
      modalDialog: store.getters.dialog,
      meta: [],
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      kcStatus: '',
      total: 0,
      venueId: sessionStorage.getItem('venueId'),
      filters: {},
      listLoading: false,
      subLoading: false,
      detail: [{}],
      tableData: [],
      multipleSelection: [],
      showDetails: false,
      showAddStudent: false,
      timeId: '',
      studentNum: '',
      realNum: '',
      currentPage: 1,
      pageSize: 10
    }
  },
  activated() {
    this.$refs.table.doLayout()
  },
  methods: {
    showStudent(e) {
      this.tempCourseRow = { ...e }
      this.showDetails = true
      this.timeId = e.timeId
      this.kcStatus = e.status
      this.refrshCourseTimeStudentList()
      this.studentNum = e.studentNum
      this.realNum = e.realNum
    },
    showStudents(e) {
      this.tempCourseRow = { ...e }
      this.isShowStudents = true
      this.timeId = e.timeId
      this.kcStatus = e.status
      this.refrshCourseTimeStudentList()
      this.studentNum = e.studentNum
      this.realNum = e.realNum
    },
    showSchedule(row) {
      this.isShowScheduleCardAdd = true
      this.$nextTick(() => {
        this.$refs.ScheduleCardAddRef.isShowModal = true
        this.$refs.ScheduleCardAddRef.courseId = this.courseId
        this.$refs.ScheduleCardAddRef.classId = this.classId
        this.$refs.ScheduleCardAddRef.param.site = this.site
        this.$refs.ScheduleCardAddRef.param.teacherId = this.teacherId
        this.$refs.ScheduleCardAddRef.getDetail()
        if (row && row.timeId) {
          this.$refs.ScheduleCardAddRef.timeId = row.timeId
          setTimeout(() => {
            this.$refs.ScheduleCardAddRef.getCourseTime()
          })
        }
      })
    },
    getList(page) {
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      this.pagination = pagination
      this.listLoading = true
      courseTimeList({ pagination, param: { venueId, ...filters, classId: this.classId, courseId: this.courseId }})
        .then(res => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.total = res.totalCount
          }
        }).catch(() => {
          this.listLoading = false
        })
    },
    closeDrawer() {
      this.isShowDrawer = false
      this.$emit('close')
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    updateStatus(e) {
      const that = this
      this.$confirm('确认删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteCourseTime({ param: { timeId: e.timeId }})
            .then(res => {
              if (res.errorCode === '000000') {
                that.$message.success('删除成功')
                that.getList(1)
              }
            })
        })
    },
    clearList() {
      this.filters = {}
      this.getList(1)
    },
    getStudentList() {
      const venueId = sessionStorage.getItem('venueId')
      courseStudentList({ param: { venueId, timeId: this.timeId, courseId: this.courseId }})
        .then(res => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.tableData = res.recordList || []
          }
        }).catch(() => {
          this.listLoading = false
        })
    },
    StuSizeChange(val) {
      this.studentPagination.rows = val
      this.refrshCourseTimeStudentList(1)
    },
    clearStudent() {
      this.studentFilter = {}
      this.refrshCourseTimeStudentList(1)
    },
    refrshCourseTimeStudentList(page) {
      if (page) {
        this.studentPagination.page = page
      }
      const { studentPagination, studentFilter } = this
      courseTimeStudentList({
        param: { timeId: this.timeId, ...studentFilter },
        pagination: studentPagination
      })
        .then(res => {
          if (res.errorCode !== '000000') return
          this.detail = res.recordList
          this.stuTotal = res.totalCount
        })
    },
    rowCanSelect(row, index) {
      return !(row.selected === true)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 页面切换方法
    handleCurrentChange(val) {
      this.currentPage = val
    },
    deleteStu(id) {
      this.$confirm('此操作将删除该学员 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          courseTimeDelStudent({ param: { id }})
            .then((res) => {
              if (res.errorCode !== '000000') return
              this.$message.success('删除成功')
              this.refrshCourseTimeStudentList()
              this.getStudentList()
              this.getList(1)
            })
        })
        .catch(() => {
          // this.$message.info('已取消删除')
        })
    },
    toStudentAdd() {
      this.showAddStudent = true
      this.multipleSelection = []
      this.getStudentList()
    },
    cancelAddStudent() {
      this.showAddStudent = false
    },
    confirmAddStudent() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择学员')
        return false
      }
      const studentList = []
      this.multipleSelection.forEach((e) => {
        studentList.push({ id: e.id, studentId: e.studentId })
      })
      this.subLoading = true
      courseTimeAddStudent({
        param: {
          studentList, timeId: this.timeId, courseId: this.courseId
        }
      })
        .then((res) => {
          this.subLoading = false
          if (res.errorCode === '000000') {
            this.showAddStudent = false
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.refrshCourseTimeStudentList()
            this.getList()
          }
        }).catch(() => {
          this.subLoading = false
        })
    }

  }
}
</script>
<style lang="scss" scoped>
.dialog-title {
  margin-bottom: 12px;
  color: #333;
}
.studentNum{
  color:#435EBE;
  cursor: pointer;
}
</style>
